/**
 * Created by zhouli on 18/11/28
 * 选择账套，选择成本中心，选择成本中心项
 */
import React from 'react';
import {connect} from 'react-redux';
import {Modal, Input, Tag, Icon, Select, Button, Table, Popover, Badge, Cascader, message} from 'antd';
import {deepCopy, messages} from 'share/common';
import CCService from 'containers/setting/cost-center/cost-center.service';
import SACCService from 'components/template/select-all-cost-center-item/select-all-cost-center-item.service.js'
import 'styles/components/template/select-all-cost-center-item/select-all-cost-center-item.scss';
const Option = Select.Option;
//账套与成本中心级联
let options = [];
class CostCenterSelectForReport extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      options,//账套与成本中心
      visible: false,
      columns: [
        {
          title: messages('data-center.key28')/*成本中心项名称*/,
          dataIndex: "name",
          width: '40%',
          render: text => <span>{text ? <Popover
            overlayStyle={{width: 200}}
            placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('data-center.key5'/*编码*/),
          dataIndex: "code",
          width: '20%',
          render: text => <span>{text ? <Popover
            overlayStyle={{width: 200}}
            placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          //状态
          title: messages('data-center.key6'/*状态*/),
          dataIndex: 'enabled',
          width: '20%',
          render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={enabled ? messages("common.status.enable") : messages("common.status.disable")}/>)
        },
      ],
      // 成本中心项翻页
      pagination: {
        total: 0,
        page: 0,
        pageSize: 10,
      },
      loading: false,
      data: [],//成本中心项
      rowSelection: {
        type: 'checkbox',
        selectedRowKeys: [],
        onChange: this.onSelectChange,
      },
      selectedValue: [],//[账套，成本中心]
      defaultSelectedValue: [],//[setofbookid],成本中心不方便确定，就让用户选择
      selectedData: [],  //已经选择的数据项
      costCenterItemName: "",//关键字搜索
    };
  }

  initData = (originSelectedData) => {
    let {rowSelection} = this.state;
    let originD = deepCopy(originSelectedData);
    if(this.props.isSingle){
      rowSelection.type = 'radio';
    }else {
      rowSelection.type = 'checkbox';
    }
    rowSelection.selectedRowKeys = originD.map(item => {
      return item.costCenterItemOID
    });
    this.setState({
      rowSelection,
      selectedData: originD
    })
  }

  componentDidMount() {
    this.initData(this.props.originSelectedData);
    this.getTenantAllSobCostCenter();
  }

  componentWillReceiveProps(nextProps) {
    // this.props.originSelectedData = nextProps.originSelectedData;
    this.initData(nextProps.originSelectedData);
  }

  //获取全部账套，用第一个账套，获取下面的全部成本中心
  getTenantAllSobCostCenter = () => {
    this.setState({
      loading: true,
    })
    SACCService.getTenantAllSobCostCenter()
      .then(res => {
        let _options = SACCService.delOptions(res.data);
        this.setState({
          loading: false,
          defaultSelectedValue: _options ? [_options[0].value] : [],
          options: _options ? _options : []
        })
      })
  }

  //选择账套成本中心之后，加载对应的成本中心项
  getAllCostCenterItemList = () => {
    let pagination = this.state.pagination;
    let selectedValue = this.state.selectedValue;
    if(selectedValue[1] === undefined){
      message.warning(messages('components.key774')/*请先选择成本中心*/);
      this.setState({
        loading: false,
      })
      return;
    }
    let params = {
      enable: true,
      page: pagination.page,
      size: pagination.pageSize,
      keyword: this.state.costCenterItemName,//成本中心项名称与code
      sort: null//是否安装code排序
    }
    CCService.getCostCenterItemsAll(selectedValue[1], params)
      .then(response => {
        pagination.total = response.total;
        pagination.current = params.page + 1;
        this.setState({
          data: response.data,
          loading: false,
          pagination
        })
      })
  }

  // 多列选择---start
  //选项改变时的回调，重置selection
  onSelectChange = (selectedRowKeys, selectedRows) => {
    let {rowSelection,selectedData} = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    selectedRows.map(item => {
      selectedData.addIfNotExistObj(item,'costCenterItemOID')
    });
    this.setState({
      rowSelection,
      selectedData
    });
  };

  handleRowClick = (record) => {
    let costCenterItemOID = record.costCenterItemOID;
    let {rowSelection, selectedData} = this.state;
    if (rowSelection.selectedRowKeys.delete(costCenterItemOID) > -1) {
      selectedData.deleteObj(record, 'costCenterItemOID');
    } else {
      selectedData.push(record);
      rowSelection.selectedRowKeys.push(costCenterItemOID);
    }
    this.setState({
      selectedData,
      rowSelection
    });
  };
  // 多列选择---end

  //显示模板
  showModel = () => {
    this.initData(this.props.originSelectedData);
    this.setState({
      visible: true,
    })
  }
  //点取消
  handleCancel = () => {
    let {rowSelection} = this.state;
    let originD = deepCopy(this.props.originSelectedData);
    rowSelection.selectedRowKeys = originD.map(item => {
      return item.costCenterItemOID
    })
    this.setState({
      selectedData: originD,
      rowSelection,
      visible: false
    })
    this.props.onCancel && this.props.onCancel(this.props.originSelectedData);
  }
  //点击确定
  handleOk = () => {
    this.setState({
      visible: false
    })
    let {selectedData} = this.state;
    this.props.onConfirm && this.props.onConfirm(selectedData);
  }
  //搜索成本中心项
  emitEmptyForDep = () => {
    this.userNameInput.focus();
    this.setState({costCenterItemName: ''}, () => {
      this.onChangeCostCenterItemName();
    });
  }
  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        page: pagination.current - 1,
        pageSize: pagination.pageSize
      }
    }, () => {
      this.getAllCostCenterItemList();
    })
  };
  //搜索成本中心项
  onChangeCostCenterItemName = (e) => {
    let costCenterItemName = "";
    if (e) {
      costCenterItemName = e.target.value;
    }
    this.setState({
      costCenterItemName: costCenterItemName,
      loading: true
    }, () => {
      this.getAllCostCenterItemList();
    });
  }
  onMouseLeaveDepTag = (e) => {
    e.stopPropagation();
  };
  onMouseEnterDepTag = (e) => {
    e.stopPropagation();
  };
  //清除已经选择的成本中心
  onCloseDepTag = (e) => {
    e.stopPropagation();
    let {rowSelection} = this.state;
    rowSelection.selectedRowKeys = [];
    this.setState({
      selectedData: [],
      rowSelection
    }, () => {
      this.props.onClear && this.props.onClear(this.state.selectedData);
    })
  };
  //删除一个已经选择了的成本中心项
  removeItem = (record) => {
    let costCenterItemOID = record.costCenterItemOID;
    let {rowSelection, selectedData} = this.state;
    rowSelection.selectedRowKeys.delete(costCenterItemOID);
    selectedData.deleteObj(record, 'costCenterItemOID');
    this.setState({
      selectedData,
      rowSelection
    });
  }
  renderSelectedVaule = () => {
    let selectedData = deepCopy(this.state.selectedData);
    if (selectedData.length > 0) {
      return selectedData.map((item, index) => {
        return <div className="show-selected-list" key={index}>
          <Icon type="team"/>
          <span className="selected-dep-item-name">
            {item.name}
          </span>
          <Icon type="close-circle"
                key={item.index}
                onClick={() => this.removeItem(item)}/>
        </div>
      })
    } else {
      return <div className='show-selected-list-empty'>{messages('components.key725')/*请选择成本中心项*/}</div>;
    }
  }
  //渲染值
  renderVauleText = () => {
    let selectedData = deepCopy(this.state.selectedData);
    if (selectedData.length > 0) {
      return selectedData.map((item, index) => {
        return <Tag key={index}>{item.name}</Tag>;
      })
    } else {
      return messages('data-center.key27')/*请选择*/;
    }
  }
  //渲染值后面的关闭icon class
  renderVauleClass = () => {
    let class_name1 = "f-right select-dep-close-wrap";
    let class_name2 = "f-right select-dep-close-wrap select-dep-close-wrap-show";
    if (this.state.selectedData.length > 0) {
      return class_name2;
    } else {
      return class_name1;
    }
  }
  //账套/成本中心级联变化
  onChange = (value, selectedOptions) => {
    let pagination = this.state.pagination;
    pagination.total = 0;
    pagination.page = 0;
    if (value.length && value.length === 2) {
      this.setState({
        pagination,
        selectedValue: value
      }, () => {
        this.getAllCostCenterItemList();
      });
    } else {
      //请选择账套/成本中心
      this.setState({
        data: [],
        pagination
      })
    }
  };

  render() {
    const {costCenterItemName,visible,options,defaultSelectedValue,
      columns,data,pagination,loading,rowSelection} = this.state;
    const {needCloseIcon,disabled} = this.props;
    const suffix = costCenterItemName ? <Icon type="close-circle" onClick={this.emitEmptyForDep}/> : null;
    return (
      <div className="select-all-cost-center-item">
        <div className="input-wrap" onClick={!disabled && this.showModel}>
          <div className='input'>
            {this.renderVauleText()}
          </div>
          {!disabled &&
          needCloseIcon && <div className={this.renderVauleClass()}
                                        onMouseLeave={this.onMouseLeaveDepTag}
                                        onMouseEnter={this.onMouseEnterDepTag}
                                        onClick={this.onCloseDepTag}>
            <Icon type="close-circle" className="closeCircle"/>
          </div>}
          <div className='clear'/>
        </div>
        <Modal
          width={800}
          className="select-all-cost-center-item-modal"
          title={messages('components.key725')/*请选择成本中心项*/}
          closable={false}
          visible={visible}
          footer={[
            <Button key="back"
                    onClick={this.handleCancel}>
              {messages('common.cancel')}
            </Button>,
            <Button key="submit"
                    type="primary"
                    onClick={this.handleOk}>
              {messages('common.ok')}
            </Button>,
          ]}
        >
          <div className='f-left show-select'>
            <div className='cascader-wrap'>
              <div className='cascader-name'>{messages('components.key726')/*请先选择账套/成本中心*/}</div>
              <Cascader
                popupClassName='class-for-cascader-cost-center'
                style={{"width": "400"}}
                options={options}
                onChange={this.onChange}
                defaultValue={defaultSelectedValue}
                changeOnSelect
              />
            </div>
            <div>
              <div className="table-header-inp">
                {/*输入成本中心项名称或编码*/}
                <Input
                  style={{"width": "400"}}
                  className='cost-center-item-name-search'
                  key={'costCenterItemName-search'}
                  placeholder={messages('data-center.key8'/*输入成本中心项名称或编码*/)}
                  prefix={<Icon type="search" className='font-disabled'/>}
                  suffix={suffix}
                  value={costCenterItemName}
                  onChange={this.onChangeCostCenterItemName}
                  ref={node => this.userNameInput = node}
                />
              </div>
              <div className="table-wrap">
                <Table columns={columns}
                       dataSource={data}
                       pagination={pagination}
                       loading={loading}
                       rowKey="costCenterItemOID"
                       bordered
                       onRow={record => ({onClick: () => this.handleRowClick(record)})}
                       rowSelection={rowSelection}
                       onChange={this.onChangePager}
                       size="middle"/>
              </div>
            </div>
          </div>
          <div className='f-right show-selected'>
            <div className='show-selected-title'>{messages('components.key727')/*已经选择的成本中心项*/}</div>
            <div className='show-selected-list-wrap'>
              {this.renderSelectedVaule()}
            </div>
          </div>
          <div className='clear'/>
        </Modal>

      </div>
    );
  }
}

CostCenterSelectForReport.propTypes = {
  needCloseIcon: React.PropTypes.bool,//不要清除按钮
  isSingle: React.PropTypes.bool,//是不是单选
  disabled: React.PropTypes.bool,
  onConfirm: React.PropTypes.func,// 点击确认之后的回调：返回结果
  onCancel: React.PropTypes.func,//点击取消的时候
  onClear: React.PropTypes.func,//点击清除所有已经选择了的
  originSelectedData: React.PropTypes.any,//被选择了的数据
};
//这个数据用户测试组件
let testSelectedData = [
  {
    "id": "254480",
    "costCenterItemOID": "4caccb54-307f-4ef1-9146-df026d24d7c3",
    "name": "121",
    "code": "12121"
  },
  {
    "id": "240758",
    "costCenterItemOID": "d9bf0eec-08d1-4c97-89fc-3158d0a68b7f",
    "name": "电脑",
    "code": "121212"
  }
]
CostCenterSelectForReport.defaultProps = {
  needCloseIcon: true,
  isSingle: false,
  disabled: false,
  originSelectedData: []//testSelectedData
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
  }
}

export default connect(mapStateToProps)(CostCenterSelectForReport);



